package org.csu.onlineedubackend.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.dto.ChatRequest;
import org.csu.onlineedubackend.dto.ChatResponse;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.SparkAiService;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/chat")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true", maxAge = 3600)
public class AIChatController {

    private final SparkAiService sparkAiService;

    @PostMapping("/send")
    public CommonResponse<ChatResponse> sendMessage(
            @RequestBody ChatRequest request, 
            @RequestParam(required = false) String token,
            HttpServletRequest httpRequest) {
        try {
            // 打印所有请求头，用于调试
            log.info("AI聊天请求头信息:");
            Enumeration<String> headerNames = httpRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                log.info("{}: {}", headerName, httpRequest.getHeader(headerName));
            }
            // 验证用户身份
            Integer userId;
            try {
                userId = StpUtil.getLoginIdAsInt();
                log.info("从StpUtil获取到用户ID: {}", userId);
            } catch (NotLoginException e) {
                // 尝试从请求头中获取token
                String headerToken = httpRequest.getHeader("satoken");
                if (headerToken != null && !headerToken.isEmpty()) {
                    try {
                        log.info("从请求头中获取到token: {}", headerToken);
                        Object loginIdObj = StpUtil.getLoginIdByToken(headerToken);
                        if (loginIdObj != null) {
                            userId = Integer.parseInt(loginIdObj.toString());
                            log.info("从请求头token获取到用户ID: {}", userId);
                            
                            // 处理AI聊天请求
                            log.info("收到聊天请求: userId={}, message={}, history.size={}",
                                userId,
                                request.getMessage(),
                                request.getHistory() != null ? request.getHistory().size() : 0);

                            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                                log.warn("消息内容为空");
                                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "消息内容不能为空");
                            }

                            ChatResponse response = sparkAiService.sendMessage(request.getMessage(), request.getHistory());
                            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "AI回复成功", response);
                        } else {
                            log.warn("请求头token无效，未能获取用户ID");
                        }
                    } catch (Exception ex) {
                        log.error("请求头token验证失败: {}", ex.getMessage());
                    }
                }
                
                // 尝试从token参数获取用户ID
                log.info("Sa-Token认证失败: {}", e.getMessage());
                
                if (token != null && !token.isEmpty()) {
                    try {
                        // 处理可能包含多个token值的情况
                        String cleanToken = token;
                        if (token.contains(",")) {
                            cleanToken = token.split(",")[0]; // 取第一个值
                            log.info("检测到多个token值，使用第一个: {}", cleanToken);
                        }
                        
                        log.info("尝试验证请求参数中的token: {}", cleanToken);
                        Object loginIdObj = StpUtil.getLoginIdByToken(cleanToken);
                        if (loginIdObj != null) {
                            userId = Integer.parseInt(loginIdObj.toString());
                            log.info("从参数token获取到用户ID: {}", userId);
                        } else {
                            log.warn("token参数无效，未能获取用户ID");
                            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "无法通过token参数获取用户ID");
                        }
                    } catch (Exception ex) {
                        log.error("Token参数验证失败: {}", ex.getMessage());
                        return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "token验证失败: " + ex.getMessage());
                    }
                } else {
                    log.warn("没有找到有效的token");
                    return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "未登录或登录已过期，请重新登录");
                }
            }

            log.info("收到聊天请求: userId={}, message={}, history.size={}",
                    userId,
                    request.getMessage(),
                    request.getHistory() != null ? request.getHistory().size() : 0);

            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                log.warn("消息内容为空");
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "消息内容不能为空");
            }

            ChatResponse response = sparkAiService.sendMessage(request.getMessage(), request.getHistory());

            // 检查是否包含错误信息
            if (response.getContent().startsWith("调用星火API异常") ||
                    response.getContent().startsWith("客户端错误") ||
                    response.getContent().startsWith("服务器错误") ||
                    response.getContent().startsWith("API请求失败")) {

                log.error("AI响应包含错误: {}", response.getContent());
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), response.getContent());
            }

            log.info("AI回复成功: {}", response.getContent().substring(0, Math.min(response.getContent().length(), 50)) + "...");

            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "AI回复成功", response);
        } catch (Exception e) {
            log.error("调用星火API失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "调用星火API失败: " + e.getMessage());
        }
    }

    @PostMapping("/send-course-intro")
    public CommonResponse<ChatResponse> sendCourseIntro(
            @RequestBody ChatRequest request, 
            @RequestParam(required = false) String token,
            HttpServletRequest httpRequest) {
        try {
            // 打印所有请求头，用于调试
            log.info("AI聊天请求头信息:");
            Enumeration<String> headerNames = httpRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                log.info("{}: {}", headerName, httpRequest.getHeader(headerName));
            }
            // 验证用户身份
            Integer userId;
            try {
                userId = StpUtil.getLoginIdAsInt();
                log.info("从StpUtil获取到用户ID: {}", userId);
            } catch (NotLoginException e) {
                // 尝试从请求头中获取token
                String headerToken = httpRequest.getHeader("satoken");
                if (headerToken != null && !headerToken.isEmpty()) {
                    try {
                        log.info("从请求头中获取到token: {}", headerToken);
                        Object loginIdObj = StpUtil.getLoginIdByToken(headerToken);
                        if (loginIdObj != null) {
                            userId = Integer.parseInt(loginIdObj.toString());
                            log.info("从请求头token获取到用户ID: {}", userId);
                            
                            // 处理AI聊天请求
                            log.info("收到聊天请求: userId={}, message={}, history.size={}",
                                userId,
                                request.getMessage(),
                                request.getHistory() != null ? request.getHistory().size() : 0);

                            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                                log.warn("消息内容为空");
                                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "消息内容不能为空");
                            }

                            ChatResponse response = sparkAiService.generateCourseIntroduction(request.getMessage(), request.getHistory());
                            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "AI回复成功", response);
                        } else {
                            log.warn("请求头token无效，未能获取用户ID");
                        }
                    } catch (Exception ex) {
                        log.error("请求头token验证失败: {}", ex.getMessage());
                    }
                }
                
                // 尝试从token参数获取用户ID
                log.info("Sa-Token认证失败: {}", e.getMessage());
                
                if (token != null && !token.isEmpty()) {
                    try {
                        // 处理可能包含多个token值的情况
                        String cleanToken = token;
                        if (token.contains(",")) {
                            cleanToken = token.split(",")[0]; // 取第一个值
                            log.info("检测到多个token值，使用第一个: {}", cleanToken);
                        }
                        
                        log.info("尝试验证请求参数中的token: {}", cleanToken);
                        Object loginIdObj = StpUtil.getLoginIdByToken(cleanToken);
                        if (loginIdObj != null) {
                            userId = Integer.parseInt(loginIdObj.toString());
                            log.info("从参数token获取到用户ID: {}", userId);
                        } else {
                            log.warn("token参数无效，未能获取用户ID");
                            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "无法通过token参数获取用户ID");
                        }
                    } catch (Exception ex) {
                        log.error("Token参数验证失败: {}", ex.getMessage());
                        return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "token验证失败: " + ex.getMessage());
                    }
                } else {
                    log.warn("没有找到有效的token");
                    return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "未登录或登录已过期，请重新登录");
                }
            }

            log.info("收到聊天请求: userId={}, message={}, history.size={}",
                    userId,
                    request.getMessage(),
                    request.getHistory() != null ? request.getHistory().size() : 0);

            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                log.warn("消息内容为空");
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "消息内容不能为空");
            }

            ChatResponse response = sparkAiService.generateCourseIntroduction(request.getMessage(), request.getHistory());

            // 检查是否包含错误信息
            if (response.getContent().startsWith("调用星火API异常") ||
                    response.getContent().startsWith("客户端错误") ||
                    response.getContent().startsWith("服务器错误") ||
                    response.getContent().startsWith("API请求失败")) {

                log.error("AI响应包含错误: {}", response.getContent());
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), response.getContent());
            }

            log.info("AI回复成功: {}", response.getContent().substring(0, Math.min(response.getContent().length(), 50)) + "...");

            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "AI回复成功", response);
        } catch (Exception e) {
            log.error("调用星火API失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "调用星火API失败: " + e.getMessage());
        }
    }

    @GetMapping("/ws-auth")
    public CommonResponse<String> getWebSocketAuthUrl() {
        // 返回空字符串，由前端直接连接本地WebSocket
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "请求成功", "");
    }

    @GetMapping("/test")
    public CommonResponse<String> test() {
        log.info("测试接口被调用");
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "请求成功", "测试成功");
    }
}
